<template>
  <el-drawer v-bind="$attrs" ref="tableFormRef" @open="openDrawer" @close="closeDrawer" destroy-on-close :close-on-click-modal="false">
    <template #header>
      <h3>{{ formMode == 'add' ? '新增' : '编辑' }}</h3>
    </template>
    <template #default>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120" label-position="left">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="formData.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="formData.password" placeholder="请输入密码" clearable />
        </el-form-item>
        <el-form-item prop="password2" label="确认密码">
          <el-input v-model="formData.password2" placeholder="请确认密码" clearable />
        </el-form-item>
        <el-form-item prop="gcaptcha" label="图形验证码">
          <el-input v-model="formData.gcaptcha" placeholder="请输入图形验证码" clearable :maxlength="4" spellcheck="false">
            <template #append>
              <el-image class="cursor-pointer" v-loading="gcaptchaLoading" :src="gcaptchaImg" @click="getGcaptcha">
                <template #error>点击获取验证码</template>
              </el-image>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称">
          <el-input v-model="formData.nickname" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item prop="phone" label="手机">
          <el-input v-model="formData.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="formData.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item prop="avatar" label="头像">
          <el-input v-model="formData.avatar" placeholder="请输入头像" clearable />
        </el-form-item>
        <el-form-item prop="department" label="部门">
          <el-input v-model="formData.department" placeholder="请输入部门" clearable />
        </el-form-item>
        <el-form-item prop="signature" label="签名">
          <el-input v-model="formData.signature" placeholder="请输入签名" type="textarea" :autosize="{ minRows: 2 }" />
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :autosize="{ minRows: 4 }" />
        </el-form-item>
        <el-form-item prop="roles" label="角色">
          <el-input v-model="formData.roles" placeholder="请输入角色" clearable />
        </el-form-item>
        <el-form-item prop="tags" label="标签">
          <el-input v-model="formData.tags" placeholder="请输入标签" clearable />
        </el-form-item>
        <el-form-item prop="birthday" label="生日">
          <el-input v-model="formData.birthday" placeholder="请输入生日" clearable />
        </el-form-item>
        <el-form-item prop="gender" label="性别">
          <el-input v-model="formData.gender" placeholder="请输入性别" clearable />
        </el-form-item>

        <el-form-item prop="status" label="状态">
          <el-switch
            v-model="formData.status"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            active-icon="Check"
            inactive-icon="Close"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElNotification } from 'element-plus'
import { cloneDeep, isEqual } from 'lodash-es'
import { assignOverrideWithHas } from '@/utils'
import { sendGraphicsCaptcha } from '@/api/auth'
import { useRegExp } from '@/hooks/useRegExp'

const props = defineProps({
  formInit: {
    type: Object,
    default: {}
  },
  formMode: {
    type: String,
    default: 'add'
  }
})

const emits = defineEmits(['submit'])

// 初始数据
const formBase = {
  id: '', // 主键
  username: '',
  password: '',
  password2: '',
  gcaptcha: '',
  nickname: '',
  phone: '',
  email: '',
  avatar: '',
  department: '',
  signature: '',
  remark: '',
  roles: '',
  tags: '',
  birthday: '',
  gender: '',
  status: 1,
  autologin: false
}
// 表单数据
const formData = ref(formBase)
// 初始数据克隆
const formBaseClone = ref()
// 校验规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      pattern: useRegExp('username').regexp,
      message: useRegExp('username').msg,
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: useRegExp('password').regexp,
      message: useRegExp('password').msg,
      trigger: 'blur'
    }
  ],
  password2: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请确认密码'))
        } else if (value !== formData.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  gcaptcha: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }]
})

// 验证码
const gcaptchaImg = ref('')
const gcaptchaLoading = ref(false)

async function getGcaptcha() {
  gcaptchaLoading.value = true
  const res = await sendGraphicsCaptcha({ type: 'register' })
  gcaptchaImg.value = res.data
  gcaptchaLoading.value = false
  // 置空图形验证码输入框
  formData.value.gcaptcha = ''
}

const tableFormRef = ref() // 抽屉
const formRef = ref() // 表单

// 抽屉打开回调
function openDrawer() {
  // 表单数据初始化更新
  formData.value = assignOverrideWithHas(cloneDeep(formBase), props.formInit)
  /**
   * 克隆一个初始数据
   */
  formBaseClone.value = cloneDeep(formData.value)
}

// 抽屉关闭回调
function closeDrawer() {}

// 关闭抽屉
function cancel() {
  tableFormRef.value.handleClose()
}
// 确认提交表单
function confirm() {
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      // 对比数据是否发生变化
      if (isEqual(formBaseClone.value, formData.value)) {
        // 未变化则提示并关闭抽屉
        ElNotification({
          title: 'Info',
          message: '数据未变更',
          type: 'info'
        })
        tableFormRef.value.handleClose()
        return
      }

      emits('submit', { data: formData.value, mode: props.formMode })
      // tableFormRef.value.handleClose()
    } else {
      console.log('==== 校验失败 :', fields)
    }
  })
}
</script>

<style lang="scss"></style>
